from turbogears import expose, redirect
from mnemoply._renewed_lib.crud import CRUDController, ItemActionsTab, TableCol
from mnemoply._renewed_lib.for_lookup import LocalMenuItem
from mnemoply.utils import PhoneFormat
from mnemoply._renewed_model.field import Account as model_Account, Personality, GroupReserve,\
                                         EducationAgreement, AccountCashOperation, StudentNew
                                        
import mnemoply._renewed_lib.widgets as widgets
from mnemoply.model import Customer, Student, StudentAgreement
from mnemoply.mass_actions import MassAction
from mnemoply.controllers import Report
from mnemoply.utils import objs2ids

class MAPrint(MassAction):
    title = _("Print")
    name = "account_print"
    read_only = True
    target_class = model_Account

    def call(self, objs):
        return Report.generate('AccountPrint',
            ids=objs2ids(objs),
        )


class PersonalityTab(ItemActionsTab):
    title = _("Personality")
    name = "personality_tab"
    ma_class_name = 'Personality'

    def getRecords(self, obj):
        pers = list(Personality.selectBy(account=obj))
        pers.sort(key=lambda x: x.title)
        return pers

class AgreementTab(ItemActionsTab):
    title = _("Agreement")
    name = "agreement_tab"
    ma_class_name = 'Personality'

    def getRecords(self, obj):
        agrs = [a for a in EducationAgreement.selectBy(account=obj) if  a.dateCreation]
        agrs.sort(key=lambda x: x.title)
        return agrs

class GroupReserveTab(ItemActionsTab):
    title = _("Group reserve")
    name = "group_reserve_tab"
    ma_class_name = 'Personality'

    def getRecords(self, obj):
        agrs = [GroupReserve.get(a.id) for a in EducationAgreement.selectBy(account=obj) if not a.dateCreation]
        agrs.sort(key=lambda x: x.title)
        return agrs

class AccountCashOperationTab(ItemActionsTab):
    title = _("Account cash operation")
    name = "cash_operation_tab"
    ma_class_name = 'Personality'

    def getRecords(self, obj):
        opers = list(AccountCashOperation.selectBy(account=obj))
        opers.sort(key=lambda x: x.title)
        return opers

class AccountController(CRUDController):
    controller_name = "Account"
    model_object = model_Account
    lookup_columns = [
        TableCol(name='number', caption=_('Account')),
        TableCol(name='phones', caption=_('Phones')),
        TableCol(name='personality', caption=_('Personality')),
        TableCol(name='groups', caption=_('Groups')),
        TableCol(name='groups12', caption='%s-%s'%(_('Groups'),2012)),
        TableCol(name='groups13', caption='%s-%s'%(_('Groups'),2013)),
        TableCol(name='count_student', caption=_('Student')),
        TableCol(name='count_customer', caption=_('Customer')),
        TableCol(name='count_personality', caption=_('Count')),
   ]

    edit_fields = [
        'phone_main',
        'phones_more',
        'sourceID'
        ]

    view_fields =[
        'number',
        'phone_main',
        'phones_more',
        'sourceID'
        ]
    add_fields = view_fields
    item_tabs = [PersonalityTab(),
                 AgreementTab(),
                 GroupReserveTab(),
                 AccountCashOperationTab()]
    widget_list = dict(number=widgets.getFreeAccount)

    @expose(format="json")
    def find(self, searchString=None):
        return self.phone_find(searchString)


    def phone_find(self, searchString=None):
        searchString=searchString.replace('-', '').replace(' ', '').replace('(', '').replace(')', '').replace('+7','8')
        return CRUDController.find(self,
                                   searchString=searchString,
                                   obj_condition=lambda obj: obj.searchphones,
                                   exposed_method=lambda obj: "%s " % (obj.allphones), )

    @expose()
    def check_phone(self, obj=None,tg_errors=None, **kw):
        str_phone = PhoneFormat.to_python(kw['phone_main'])
        if (str_phone == PhoneFormat.bad_str()):
            res = "%s"%(PhoneFormat.bad_str(True))
            return dict(result_check_phone = res)
        if obj:
            id = obj.id
        else:
            id = 0
        dict_phone = PhoneFormat.from_python(str_phone)
        list_search =  self.phone_find(dict_phone['num']).get('textItems','')
        search_res = [a[0] for a in list_search if a[1] != id]
        res='%s %s\n'%(_('Find like:'),len(search_res))
        if search_res:
            res +='\n'.join(search_res)
        return dict(result_check_phone=res)
    check_phone.expose_object = True

    @expose()
    def phone_info(self,**kw):        
        field =i =''
        res=_('*No value*')
        per = None
        field = kw.get('phoneID','')
        if field:        
            i = field.get('hidden','0')
        if i:
            pers = list(Personality.select('phone_id=%s'%i))
            pers.sort(key=lambda x: x.title)
            res = [x.title for x in pers]
            res ='\n'.join(res)
        return dict(info_phoneID=res)
    phone_info.expose_object = True

exposed = AccountController()

##next code for transfer from old version
## begin transfer:
    #def create_menu(self, state, for_row=False):
    #    menu = CRUDController.create_menu(self,state,for_row)
    #    if self.hasMenu('transfer',state, for_row):
    #         menu.append(LocalMenuItem(widget=widgets.URLLink,  params=dict(link='transfer',text='Transfer' )),)
    #    return menu
    #
    #def hasMenu(self, action, state, for_row = False):
    #    if action == 'transfer':
    #        where = (state=='show') or for_row
    #        return where
    #    res = CRUDController.hasMenu(self, action, state, for_row)
    #    return res
    #
    #@expose(template="genshi:mnemoply.templates.create_personality")
    #def transfer(self, obj):
    #    def getRecords(obj, is_student=True):
    #        model_class = Student if is_student else Customer
    #        agrs = list(model_class.selectBy(family_id=obj.id))
    #        agrs.sort(key=lambda x: x.title)
    #        return agrs
    #    return dict(obj=obj, students=getRecords(obj), customers = getRecords(obj, False))
    #transfer.expose_object = True
    #
    #@expose()
    #def add_agreements(self, obj,old):
    #    agr_old = StudentAgreement.get(old)
    #    agr_2012 = GroupReserve(
    #        account = obj,
    #        dateEnter = agr_old.dateEnterAgreement,
    #        student = agr_old.student.personality,
    #        customer = agr_old.customer.personality,
    #        group = agr_old.group,
    #    )
    #    agr_old.groupReserve = agr_2012
    #    agr_2013 = GroupReserve(
    #        account = obj,
    #        student = agr_old.student.personality,
    #        customer = agr_old.customer.personality,
    #        group = 0,
    #    )
    #    raise redirect ('/GroupReserve_new/%s/edit_req'%agr_2013.id)
    #
    #add_agreements.expose_object = True
    #
    #@expose() 
    #def add_student(self, obj,student_id):
    #    st = Student.get(student_id)
    #    year1 = st.first_agreement.initialPlan.year
    #    class1 = st.schoolForm -(st.last_agreement.initialPlan.year - year1)
    #    new_st=StudentNew(surname=st.surname,
    #                      forename=st.forename,
    #                      patronymic = st.patronymic,
    #                      accountID=obj.id,
    #                      email=st.email,
    #                      dateEnter=st.enteringDate,
    #                      isStudent=True,
    #                      birthday=st.birthday,
    #                      student_type=1,
    #                      surname_translit=st.surname_translit,
    #                      forename_translit=st.forename_translit,
    #                      patronymic_translit= st.patronymic_translit,
    #                      school_name=st.schoolName,
    #                      school_form =class1,
    #                      academic_year_admission = year1
    #                      )
    #    st.personality = new_st
    #    raise redirect ('/Student_new/%s/edit_req'%new_st.id)
    #add_student.expose_object = True
## end transfer    
    
